package com.ggs.starbug.controller;


import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.ggs.starbug.entity.PageVO;
import com.ggs.starbug.entity.R;
import com.ggs.starbug.entity.User;
import com.ggs.starbug.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import static com.ggs.starbug.config.rabbitmq.RabbitMQConstants.*;

/**
 * <p>
 * 用户基础信息表 前端控制器
 * </p>
 *
 * @author Starbug
 * @since 2021-09-23
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostMapping("/add")
    public R addUser(@RequestBody User user) {
        user.setId(IdWorker.getId());
        return userService.save(user) ?
                R.ok().message("添加成功").data(user) :
                R.failed().message("添加失败啦");
    }

    @GetMapping("/page/{page}/{size}")
    public R pageQuery(@PathVariable("page") int page,
                       @PathVariable("size") int size) {
        PageVO pageVO = userService.pageQuery(page, size);
        return R.ok().data(pageVO);
    }

    @PostMapping("/deadLetter/{ttlTime}")
    public R deadLetter(@RequestBody User user, @PathVariable String ttlTime) {
        log.info("发送一条消息，内容：{},ttl时间：{}", user.getId(), ttlTime);
        rabbitTemplate.convertAndSend(NORMAL_EXCHANGE, NORMAL_ROUTING_KEY_A, user, new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                message.getMessageProperties().setExpiration(ttlTime);
                message.getMessageProperties().setHeader("hello", "starbug");
                return message;
            }
        });
        return R.ok();
    }

    @PostMapping("/delayedLetter/{delayedTime}")
    public R deadLetter(@RequestBody User user, @PathVariable Integer delayedTime) {
        log.info("发送一条延迟消息，内容：{},延迟时间：{}", user.getId(), delayedTime);
        rabbitTemplate.convertAndSend(DELAYED_EXCHANGE, DELAYED_ROUTING_KEY, user, (message) -> {
            message.getMessageProperties().setDelay(delayedTime);
            message.getMessageProperties().setHeader("hello", "starbug");
            return message;
        });
        return R.ok();
    }

}
